﻿using Shop.Model.DB;
using Shop.RemoteModel;
using Shop.RemoteModel.PageTemplate.Model;
using Shop.Repository;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Shop.Collect.lmpl
{
    internal class PageTemplateCollect : IPageTemplateCollect
    {
        private readonly IPageTemplateRepository _Repository;

        public PageTemplateCollect ( IPageTemplateRepository repository )
        {
            this._Repository = repository;
        }
        public long Add ( PageTemplateAdd data )
        {
            if ( this._Repository.IsExist(c => c.TemplatePlace == data.TemplatePlace && c.UseRange == data.UseRange && c.TemplateName == data.TemplateName) )
            {
                throw new ErrorException("shop.page.template.name.repeat");
            }
            return this._Repository.Add(data);
        }
        public DBPageTemplate Get ( long id )
        {
            return this._Repository.Get(id);
        }
        public Result Get<Result> ( long id ) where Result : class
        {
            return this._Repository.Get<Result>(id);
        }
        public bool Set ( DBPageTemplate source, PageTemplateSet set )
        {
            if ( source.Status == PageStatus.启用 )
            {
                throw new ErrorException("shop.page.template.not.allow.update");
            }
            string[] cols = source.Merge(set);
            if ( cols.IsNull() )
            {
                return false;
            }
            if ( cols.Contains("TemplateName") && this._Repository.IsExist(c => c.TemplatePlace == source.TemplatePlace && c.UseRange == source.UseRange && c.TemplateName == set.TemplateName) )
            {
                throw new ErrorException("shop.page.template.name.repeat");
            }
            source.EditTime = DateTime.Now;
            return this._Repository.Update(source, cols.Add("EditTime"));
        }
        public bool Enable ( DBPageTemplate source )
        {
            if ( source.Status == PageStatus.启用 )
            {
                return false;
            }
            long id = this._Repository.Get(c => c.TemplatePlace == source.TemplatePlace && c.UseRange == source.UseRange && c.Status == PageStatus.启用, c => c.Id);
            if ( id == source.Id )
            {
                return false;
            }
            return this._Repository.Enable(source, id);
        }
        public void Delete ( DBPageTemplate source )
        {
            if ( source.Status != PageStatus.起草 )
            {
                throw new ErrorException("shop.page.template.not.allow.delete");
            }
            this._Repository.Delete(source.Id);
        }
        public Result[] Query<Result> ( PageTemplateQuery query, IBasicPage paging, out int count ) where Result : class, new()
        {
            return this._Repository.Query<Result>(query, paging, out count);
        }
    }
}
